<template>
  <div :class="{ 'ant-card': !isDialog }">
    <div class="table-page-search-wrapper">
      <a-form-model
        layout="inline"
        :model="searchForm"
        @submit.prevent="fetch"
        ref="searchForm"
      >
        <a-form-model-item label="权限名：" prop="name" v-if="!isDialog">
          <a-input v-model="searchForm.name"></a-input>
        </a-form-model-item>
        <a-form-model-item label="url：" prop="url" v-if="!isDialog">
          <a-input v-model="searchForm.url"></a-input>
        </a-form-model-item>
        <a-form-model-item label="权限字符串：" prop="permission">
          <a-input v-model="searchForm.permission"></a-input>
        </a-form-model-item>
        <a-form-model-item>
          <a-button type="primary" html-type="submit">查询</a-button>
        </a-form-model-item>
        <a-form-model-item>
          <a-button type="default" @click="resetForm('searchForm')"
            >重置
          </a-button>
        </a-form-model-item>
      </a-form-model>
    </div>
    <div class="table-operator" v-if="!isDialog">
      <a-button type="primary" html-type="submit" @click="showModal">
        新增
      </a-button>
    </div>
    <a-modal
      title="编辑"
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form-model
        layout="horizontal"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 12, offset: 1 }"
        :model="form"
        @submit.prevent="fetch"
        ref="form"
        :rules="rules"
      >
        <a-form-model-item label="id：" prop="id" v-show="false">
          <a-input v-model="form.id"></a-input>
        </a-form-model-item>
        <a-form-model-item label="名称：" prop="name">
          <a-input v-model="form.name"></a-input>
        </a-form-model-item>
        <a-form-model-item label="url：" prop="url">
          <a-input v-model="form.url"></a-input>
        </a-form-model-item>
        <a-form-model-item label="权限字符串：" prop="permission">
          <a-input v-model="form.permission"></a-input>
        </a-form-model-item>
        <a-form-model-item label="描述：" prop="description">
          <a-input v-model="form.description"></a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-table
      :rowSelection="
        isDialog
          ? { selectedRowKeys: selectedRowKeys, onChange: onSelectChange }
          : null
      "
      :dataSource="data"
      :loading="loading"
      rowKey="id"
      bordered
      :pagination="pagination"
      @change="handleTableChange"
    >
      <a-table-column title="id" dataIndex="id" />
      <a-table-column title="名称" dataIndex="name" />
      <a-table-column title="url" dataIndex="url" />
      <a-table-column title="权限字符串" dataIndex="permission" />
      <a-table-column title="描述" dataIndex="description" v-if="!isDialog" />
      <a-table-column title="操作" key="action" v-if="!isDialog">
        <template v-slot="record">
          <a @click.prevent="edit(record.id)">编辑</a>
          <a-divider type="vertical" />
          <a @click.prevent="del(record.id)">删除</a>
        </template>
      </a-table-column>
    </a-table>
  </div>
</template>

<script>
import { list, add, getOne, del } from "@/api/Resource";

export default {
  name: "index",
  props: {
    isDialog: {
      type: Boolean,
      default: false
    },
    resourceIds: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      pagination: {
        total: 0,
        current: 1,
        pageSize: 10, //每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ["5", "10", "20"], //每页中显示的数据
        showTotal: total => `共有 ${total} 条数据` //分页中显示总的数据
      },
      //封装查询条件
      searchForm: {
        name: null,
        url: null,
        permission: null
      },
      loading: false,
      data: [],
      selectedRowKeys: [],
      //模态form 最开始隐藏
      visible: false,
      //模态form
      form: {
        id: null,
        name: null,
        url: null,
        permission: null,
        description: null
      },
      //模态form 校验规则
      rules: {
        name: [{ required: true, message: "不允许为空", trigger: "blur" }],
        url: [{ required: true, message: "不允许为空", trigger: "blur" }],
        permission: [{ required: true, message: "不允许为空", trigger: "blur" }]
      }
    };
  },
  created() {
    //弹出窗口资源分页参数
    if (this.isDialog) {
      this.pagination = {
        total: 0,
        current: 1,
        pageSize: 5, //每页中显示5条数据
        showSizeChanger: false
      };
    }
    this.fetch();
  },
  //父组件传值给子组件，父组件值改变，子组件不能重新渲染,用watch()监听值的改变
  watch: {
    resourceIds: {
      handler(newValue) {
        this.selectedRowKeys = newValue;
      },
      deep: true //深度监听
    }
  },
  methods: {
    fetch() {
      this.loading = true;
      list(
        this.pagination.current,
        this.pagination.pageSize,
        this.searchForm
      ).then(response => {
        let resp = response.data;
        if (resp.flag) {
          this.data = resp.data.results;
          this.pagination.total = resp.data.totalCount;
        }
        this.loading = false;
      });
    },
    handleTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.fetch();
    },
    onSelectChange(selectedRowKeys) {
      console.log("selectedRowKeys changed: ", selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;

      //子组件拿到了数据,要给父组件传值 $emit
      this.$emit("get-Resources", this.selectedRowKeys);
    },
    //打开新增模态窗口
    showModal() {
      this.visible = true;
      //清空上一次输入
      this.$nextTick(() => {
        // this.$nextTick()它是一个异步事件，当渲染结束 之后 ，它的回调函数才会被执行
        // 弹出窗口打开之后 ，需要加载Dom, 就需要花费一点时间，我们就应该等待它加载完dom之后，再进行调用resetFields方法，重置表单和清除样式
        this.$refs["form"].resetFields();
      });
    },
    //新增或修改
    handleOk() {
      this.$refs.form.validate(valid => {
        if (valid) {
          add(this.form).then(response => {
            let resp = response.data;
            if (resp.flag) {
              this.$message.success("编辑成功");
              //table重新取最新数据
              this.fetch();
              //隐藏dialog
              this.visible = false;
            } else {
              this.$message.error("编辑失败");
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleCancel() {
      this.visible = false;
    },
    //重置查询表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    edit(id) {
      this.showModal();

      getOne(id).then(response => {
        let resp = response.data;
        if (resp.flag) {
          //给form赋值，必有id
          this.form = resp.data;
        }
      });
    },
    del(id) {
      this.$confirm({
        title: "提示",
        content: "确定删除吗 ?",
        onOk: () => {
          del(id).then(response => {
            let resp = response.data;
            if (resp.flag) {
              this.fetch();
              this.$message.success("删除成功");
            } else {
              this.$message.error("删除失败");
            }
          });
        },
        onCancel() {}
      });
    }
  }
};
</script>

<style scoped></style>
